package yunquan.wang.base.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import yunquan.wang.base.config.AppConfig;
import yunquan.wang.base.dao.MatchType;
import yunquan.wang.base.dao.PropertyFilter;
import yunquan.wang.base.web.ajax.AjaxDone;

public abstract class WebHelper {
	private static final Logger logger = LoggerFactory
			.getLogger(WebHelper.class);

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		return requestAttributes.getRequest();
	}

	public static String getRequestParam(String name) {
		return getRequest().getParameter(name);
	}
	public static String getControllerPath() {
		String path = getRequest().getAttribute("org.springframework.web.servlet.HandlerMapping.bestMatchingPattern").toString();
		path = path.substring(0, path.lastIndexOf("/"));
		return path;
	}
	
	public static <T> T fromJsonToObject(String json, Class<T> valueType) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(json, valueType);
		} catch (JsonParseException e) {
			logger.error("JsonParseException: ", e);
		} catch (JsonMappingException e) {
			logger.error("JsonMappingException: ", e);
		} catch (IOException e) {
			logger.error("IOException: ", e);
		}
		return null;
	}
	
	public static Pageable getPage(HttpServletRequest request) {
		PageRequest page = null;
		String orderField = request.getParameter(WebConstants.ORDER_FIELD);
		String orderDirection = request.getParameter(WebConstants.ORDER_DIRECTION);
		String pageNo = request.getParameter(WebConstants.PAGE_NO);
		Integer pageInt = StringUtils.isBlank(pageNo) ? 0 : Integer
				.valueOf(pageNo) - 1;
		String pageSize = request.getParameter(WebConstants.PAGE_SIZE);
		Integer sizeInt = StringUtils.isBlank(pageSize) ? AppConfig.getPagesize()
				: Integer.valueOf(pageSize);
		if (StringUtils.isNotBlank(orderDirection)
				&& StringUtils.isNotBlank(orderField)) {
			//
			// 多个排序
			// String[] orders= StringUtils.split(orderDirection);
			// String[] fields= StringUtils.split(orderField);
			// List<Order> orderList=new ArrayList<Order>();
			// for(int i=0;i<orders.length;i++)
			// {
			// Order order=null;
			// if(orders[i].equalsIgnoreCase("DESC"))
			// {
			// order=new Order(Direction.DESC,fields[i]);
			// }
			// else
			// {
			// order=new Order(Direction.ASC,fields[i]);
			// }
			// orderList.add(order);
			// }
		if(pageInt<0)pageInt=0;//当定义小于0的时候
			page = new PageRequest(pageInt, sizeInt, new Sort(
					Direction.fromString(orderDirection), orderField));

		} else {
			if(pageInt<0)pageInt=0;//当定义小于0的时候
			page = new PageRequest(pageInt, sizeInt);
		}
		return page;

	}
	
	public static List<PropertyFilter> filterRequest(final HttpServletRequest request) {
		List<PropertyFilter> filterList = new ArrayList<PropertyFilter>();
		//从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map.
		Map<String, Object> filterParamMap = WebUtils.getParametersStartingWith(request, WebConstants.FILTER_PERFIX + "_");
		//分析参数Map,构造PropertyFilter列表
		for (Map.Entry<String, Object> entry : filterParamMap.entrySet()) {
			String filterName = entry.getKey();
			String value = (String) entry.getValue();
			//如果value值为空,则忽略此filter.
			if (StringUtils.isNotBlank(value)) {
				String matchTypeStr = StringUtils.substringBefore(filterName, "_");
				String realFilterName=StringUtils.substringAfter(filterName, "_");
				PropertyFilter filter = new PropertyFilter(realFilterName,  Enum.valueOf(MatchType.class,matchTypeStr),value);
				request.setAttribute(filterName.replace(".", "_"), value);
				filterList.add(filter);
			}
		}
		return filterList;
	}
	/**
	 * 默认保存成功
	 * @return
	 */
	public static AjaxDone saveSuccess()
	{
		AjaxDone done=new AjaxDone();
		done.setStatusCode(AjaxDone.STATUS_OK);
		done.setMessage("保存成功！");
		String isCotinue=getRequestParam(AjaxDone.CB_CONTINUTE);
		//如果是连续添加
		if(StringUtils.isNotBlank(isCotinue)&&isCotinue.equalsIgnoreCase("true"))
		{
			return done;
		}
		done.setCallbackType(AjaxDone.CB_CLOSCURENT);
	
		String targetType=getRequestParam(WebConstants.TARGET_TYPE);;
		String targetId=getRequestParam(WebConstants.TARGET_ID);
		if(StringUtils.isNotBlank(targetId)&&WebConstants.NAV_TAB.endsWith(targetType))
		{
			done.setNavTabId(targetId);
		}
		return done;
	}
	
	public static AjaxDone deleteSuccess( )
	{
		AjaxDone done=new AjaxDone();
		done.setStatusCode(AjaxDone.STATUS_OK);
	//	done.setCallbackType(AjaxDone.CB_CLOSCURENT);
		done.setMessage("删除成功！");
		String targetType=getRequestParam(WebConstants.TARGET_TYPE);;
		String targetId=getRequestParam(WebConstants.TARGET_ID);
		if(StringUtils.isNotBlank(targetId)&&WebConstants.NAV_TAB.endsWith(targetType))
		{
			done.setNavTabId(targetId);
		}
		return done;
	}

	/**
	 * 验证失败 Ajax返回
	 * 
	 * @param bindingResult
	 * @return
	 */
	public static AjaxDone validFail(BindingResult bindingResult) {
		AjaxDone done = new AjaxDone();
		done.setStatusCode(AjaxDone.STATUS_ERROR);
		List<FieldError> fieldErrors = bindingResult.getFieldErrors();
		String message="校验错误，错误原因：";
		int k=0;
		for (FieldError fieldError : fieldErrors) {
			message+="<br/>";
			k++;
			message=message+" "+k+"，"+	fieldError.getField()+""+fieldError.getDefaultMessage();
		}
		done.setMessage(message);
		return done;
	}
/**
 * 保存失败
 * @param e
 * @return
 */
	public static AjaxDone saveFail(Exception e) {
	 
		AjaxDone done = new AjaxDone();
		done.setStatusCode(AjaxDone.STATUS_ERROR);
		String message="保存失败， 原因：";
		message+="<br/>";
		message =message+"cause:"+e.getCause();
		message+=e.getMessage()+"<br/>";
		message+=e.getStackTrace()+"";

		done.setMessage(message);
		//测试期间
		e.printStackTrace();
		return done;
	}
}
